package com.fjnu.service;

import com.fjnu.annotation.ExceptionGlobalCatch;
import com.fjnu.dao.ArticleDao;
import com.fjnu.dao.UserDao;
import com.fjnu.dto.ArticleConditionDto;
import com.fjnu.dto.ArticleUpdateDto;
import com.fjnu.dto.PageResult;
import com.fjnu.entity.Article;
import com.fjnu.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@ExceptionGlobalCatch
public class ArticleService {

    @Autowired
    private ArticleDao articleDao;

    @Autowired
    private UserDao userDao;

    /**
     * 文章条件分页查询
     */
    public PageResult<Article> queryByArticleCondition(ArticleConditionDto articleCond,
                                                       Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null || pageNum < 1 || pageSize < 1) {
            return new PageResult<>(0, 0, 0L, null);
        }
        int offset = (pageNum - 1) * pageSize;
        List<Article> articles = articleDao.selectByCondition(articleCond, offset, pageSize);
        Long total = articleDao.countByCondition(articleCond);
        return new PageResult<>(pageNum, pageSize, total, articles);
    }

    /**
     * 根据ID查询文章
     */
    public Article queryById(String articleId) {
        if (articleId == null) {
            return null;
        }
        try {
            return articleDao.selectById(Integer.parseInt(articleId));
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 新增文章
     */
    @Transactional
    public Article insertArticle(Article article) {
        if (article == null || article.getUserId() == null || article.getTitle() == null
                || article.getContent() == null || article.getCategoryId() == null) {
            return null;
        }
        // 设置默认状态为草稿（0）
        article.setStatus(0);
        int rows = articleDao.insert(article);
        if (rows > 0) {
            // 返回包含自增ID的文章对象
            return articleDao.selectLastInserted(article.getUserId(), article.getTitle());
        }
        return null;
    }

    /**
     * 发布文章（单篇）
     */
    @Transactional
    public int publishArticle(String articleId, String userId) {
        if (articleId == null || userId == null) {
            return 0;
        }
        Integer aid, uid;
        try {
            aid = Integer.parseInt(articleId);
            uid = Integer.parseInt(userId);
        } catch (NumberFormatException e) {
            return 0;
        }

        // 1. 更新文章状态为发布（1）
        int updateRows = articleDao.updateStatus(aid, 1);
        if (updateRows <= 0) {
            return 0;
        }

        // 2. 更新用户积分（发布一篇+10分）
        User user = userDao.selectById(uid);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        userDao.updateScore(uid, user.getScore() + 10);
        return 1;
    }

    /**
     * 批量发布文章
     */
    @Transactional
    public int publishArticlesByBatch(String[] articleIds, String userId) {
        if (articleIds == null || articleIds.length == 0 || userId == null) {
            return 0;
        }
        Integer uid;
        try {
            uid = Integer.parseInt(userId);
        } catch (NumberFormatException e) {
            return 0;
        }

        // 转换文章ID列表
        List<Integer> ids = Arrays.stream(articleIds)
                .map(Integer::parseInt)
                .toList();

        // 1. 批量更新状态为发布（1）
        int updateRows = articleDao.batchUpdateStatus(ids, 1);
        if (updateRows != articleIds.length) {
            throw new RuntimeException("批量发布失败，部分文章不存在");
        }

        // 2. 更新用户积分（每篇+10分）
        User user = userDao.selectById(uid);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        userDao.updateScore(uid, user.getScore() + articleIds.length * 10);
        return 1;
    }

    /**
     * 更新文章
     */
    @Transactional
    public int updateArticle(ArticleUpdateDto articleUpdateDto) {
        if (articleUpdateDto == null || articleUpdateDto.getId() == null) {
            return 0;
        }
        return articleDao.updateByDto(articleUpdateDto);
    }

    /**
     * 删除文章
     */
    @Transactional
    public int removeArticle(String articleId, String userId) {
        if (articleId == null || userId == null) {
            return 0;
        }
        Integer aid, uid;
        try {
            aid = Integer.parseInt(articleId);
            uid = Integer.parseInt(userId);
        } catch (NumberFormatException e) {
            return 0;
        }

        // 1. 检查文章是否存在且属于该用户
        Article article = articleDao.selectById(aid);
        if (article == null || !article.getUserId().equals(uid)) {
            return 0;
        }

        // 2. 删除文章
        int deleteRows = articleDao.delete(aid);
        if (deleteRows <= 0) {
            return 0;
        }

        // 3. 更新用户积分（删除一篇-5分，最低0分）
        User user = userDao.selectById(uid);
        userDao.updateScore(uid, Math.max(0, user.getScore() - 5));
        return 1;
    }
}